package com.example.demo.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.example.demo.entity.Book;

@Repository
public class BookDao {

	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 查询单个的图书
	 * @return
	 */
	public Book getOne() {
		String sql = "select * from Book where id=4";
		Book result = (Book) jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper(Book.class));
		return result;
	}
	/**
	 * 查询所有的图书
	 * @return
	 */
	public List<Book> getBookAll() {
		String sql = "select * from Book";
		RowMapper<Book> rowMapper = new RowMapper<Book>() {

			@Override
			public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
				Book book = new Book();
				book.setId(rs.getInt("id"));
				book.setName(rs.getString("name"));
				book.setPrice(rs.getDouble("price"));
				return book;
			}
		};
		List<Book> object = jdbcTemplate.query(sql, rowMapper);
		return object;
	}
}
